import React, { useEffect } from 'react';
import { Table, Button, Space, Input, message, Popconfirm } from 'antd';
import { EditOutlined, DeleteOutlined, SearchOutlined, PlusOutlined } from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { fetchPassengers, deletePassenger } from '../../store/slices/passengerSlice';

const { Search } = Input;

const PassengerList = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { passengers, loading, pagination } = useSelector((state) => state.passengers);

  useEffect(() => {
    dispatch(fetchPassengers());
  }, [dispatch]);

  const handleDelete = async (id) => {
    try {
      await dispatch(deletePassenger(id)).unwrap();
      message.success('乘客删除成功');
    } catch (error) {
      message.error('删除失败: ' + error.message);
    }
  };

  const handleEdit = (id) => {
    navigate(`/passengers/edit/${id}`);
  };

  const handleSearch = (value) => {
    dispatch(fetchPassengers({ search: value }));
  };

  const columns = [
    {
      title: '姓名',
      dataIndex: 'full_name',
      key: 'full_name',
      fixed: 'left',
      width: 120,
      render: (_, record) => `${record.first_name}${record.last_name}`,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 200,
    },
    {
      title: '电话',
      dataIndex: 'phone',
      key: 'phone',
      width: 150,
    },
    {
      title: '护照号',
      dataIndex: 'passport_number',
      key: 'passport_number',
      width: 180,
    },
    {
      title: '出生日期',
      dataIndex: 'date_of_birth',
      key: 'date_of_birth',
      width: 120,
      render: (text) => text ? new Date(text).toLocaleDateString('zh-CN') : '-',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 160,
      render: (text) => new Date(text).toLocaleString('zh-CN'),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 120,
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record.id)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个乘客吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
        <Search
          placeholder="搜索姓名、邮箱或电话"
          allowClear
          enterButton={<SearchOutlined />}
          size="large"
          style={{ width: 300 }}
          onSearch={handleSearch}
        />
        <Button
          type="primary"
          icon={<PlusOutlined />}
          size="large"
          onClick={() => navigate('/passengers/create')}
        >
          添加乘客
        </Button>
      </div>
      <Table
        columns={columns}
        dataSource={passengers}
        rowKey="id"
        loading={loading}
        scroll={{ x: 1000 }}
        pagination={{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) =>
            `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
        }}
        onChange={(pagination) => {
          dispatch(fetchPassengers({
            page: pagination.current,
            page_size: pagination.pageSize,
          }));
        }}
      />
    </div>
  );
};

export default PassengerList;